package edu.msg.jthr.web.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.msg.jthr.backend.model.User;
import edu.msg.jthr.backend.service.UserService;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@EJB
	private UserService userService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	// @Override
	// protected void doGet(HttpServletRequest req, HttpServletResponse resp)
	// throws ServletException, IOException {
	//
	// RequestDispatcher rs = req.getRequestDispatcher("webpages/login.jsp");
	// rs.include(req, resp);
	// }

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher rs = request
				.getRequestDispatcher("webpages/login.jsp");
		rs.include(request, response);
	}

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		String user = request.getParameter("username");
		String pass = request.getParameter("password");
		if (validate(user, pass)) {
			RequestDispatcher rs = request
					.getRequestDispatcher("webpages/addJob.jsp");
			rs.forward(request, response);
		} else {
			RequestDispatcher rs = request
					.getRequestDispatcher("webpages/login.jsp");
			rs.include(request, response);
			out.println("<center><font color=\"red\">Username or password incorrect!</font></center>");
		}
	}

	private boolean validate(String user, String pass) {
		try {
			User temp = userService.getByName(user);
			if (temp != null) {
				String encryptedPass = userService.encryptPassword(pass);
				return temp.getUserPass().equals(encryptedPass);
			}
			return false;
		} catch (Exception e) {
			// TODO change it to false before release !
			return true;
		}
	}

}
